<template>
  <div>
    <el-form ref="form" label-width="80px">
      <el-form-item label="SPU名称">
        <el-input placeholder="请输入SPU名称" v-model="spu.spuName"></el-input>
      </el-form-item>
      <el-form-item label="品牌">
        <el-select placeholder="请选择品牌" v-model="spu.tmId">
          <el-option
            :label="trademark.tmName"
            :value="trademark.id"
            v-for="(trademark, index) in trademarkList"
            :key="trademark.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="SPU描述">
        <el-input
          type="textarea"
          rows="4"
          placeholder="描述"
          v-model="spu.description"
        ></el-input>
      </el-form-item>
      <el-form-item label="SPU图片">
        <el-upload
          action="/dev-api/admin/product/fileUpload"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :file-list="spuImageList"
          :on-success="handlerSuccess"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="" />
        </el-dialog>
      </el-form-item>
      <el-form-item label="销售属性">
        <el-select
          :placeholder="`还有${unSelectSaleAttr.length}未选择`"
          v-model="attrIdAndAttrName"
        >
          <el-option
            :label="unSelect.name"
            :value="`${unSelect.id}:${unSelect.name}`"
            v-for="(unSelect, index) in unSelectSaleAttr"
            :key="unSelect.id"
          ></el-option>
        </el-select>
        <el-button
          type="primary"
          icon="el-icon-plus"
          :disabled="!attrIdAndAttrName"
          @click="addSaleAttr"
          >添加销售属性</el-button
        >
        <el-table style="width: 100%" border :data="spu.spuSaleAttrList">
          <el-table-column type="index" label="序号" width="80px">
          </el-table-column>
          <el-table-column prop="saleAttrName" label="属性名" width="width">
          </el-table-column>
          <el-table-column prop="prop" label="属性值名称列表" width="width">
            <template slot-scope="{ row, $index }">
              <el-tag
                v-for="(tag, index) in row.spuSaleAttrValueList"
                :key="tag.id"
                closable
                :disable-transitions="false"
                @close="row.spuSaleAttrValueList.splice(index, 1)"
              >
                {{ tag.saleAttrValueName }}
              </el-tag>
              <el-input
                class="input-new-tag"
                v-if="row.inputVisible"
                v-model="row.inputValue"
                ref="saveTagInput"
                size="small"
                @blur="handleInputConfirm(row)"
              ></el-input>
              <el-button
                v-else
                class="button-new-tag"
                size="small"
                @click="addSaleAttrValue(row)"
                >添加</el-button
              >
            </template>
          </el-table-column>
          <el-table-column prop="prop" label="操作" width="width">
            <template slot-scope="{ row, $index }">
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="spu.spuSaleAttrList.splice($index, 1)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="addOruodateSpu">保存</el-button>
        <el-button
          @click="cancel">取消</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  name: "",
  data() {
    return {
      dialogImageUrl: "",
      dialogVisible: false,
      tmId: "",
      spu: { //存储SPU信息属性
        category3Id: 0,
        description: "",
        spuImageList: [],
        spuName: "",
        spuSaleAttrList: [],
      },
      trademarkList: [], //存储品牌信息
      spuImageList: [], //存储SPU图片的数据
      saleAttrList: [], //存储销售属性数据
      attrIdAndAttrName: "", //收集未选择的销售属性ID
    };
  },
  methods: {
    //照片墙删除某一个图片的回调
    handleRemove(file, fileList) {
      this.spuImageList = fileList;
    },
    //照片墙预览的回调
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    //通过修改按钮初始化spuForm数据
    initSpuData(spu) {
      // this.$API.spu.reqSpu(spu.id).then((e) => {
      //   console.log(e);
      // });
      // console.log(this.$API.spu.reqSpu(spu.id));

      let reqSpu = new Promise((res, rej) => {
        this.$API.spu.reqSpu(spu.id).then((e) => {
          res(e);
        });
      });
      let reqTrademarkList = new Promise((res, rej) => {
        this.$API.spu.reqTrademarkList().then((e) => {
          res(e);
        });
      });
      let reqSpuImageList = new Promise((res, rej) => {
        this.$API.spu.reqSpuImageList(spu.id).then((e) => {
          res(e);
        });
      });
      let reqBaseSaleAttrList = new Promise((res, rej) => {
        this.$API.spu.reqBaseSaleAttrList().then((e) => {
          res(e);
        });
      });

      Promise.all([
        reqSpu,
        reqTrademarkList,
        reqSpuImageList,
        reqBaseSaleAttrList,
      ]).then((res) => {
        console.log(res);
        this.spu = res[0].data;
        this.trademarkList = res[1].data;
        let imglist = res[2].data;
        imglist.forEach((value) => {
          //由于照片墙显示图片的数据需要数组，数组里面的元素需要有name与url字段
          //需要把服务器返回的数据进行修改
          value.name = value.imgName;
          value.url = value.imgUrl;
        });
        //把整理好的数据赋值给
        this.spuImageList = imglist;
        this.saleAttrList = res[3].data;
      });
    },
    //添加SUP
    addSpuData(category3Id) {
      this.spu.category3Id=category3Id
      this.$API.spu.reqTrademarkList().then((e) => {
        this.trademarkList = e.data;
      });

      this.$API.spu.reqBaseSaleAttrList().then((e) => {
        this.saleAttrList = e.data;
      });
    },
    //照片墙图片上传成功的回调
    handlerSuccess(response, file, fileList) {
      this.spuImageList = fileList;
    },
    //添加销售属性
    addSaleAttr() {
      const [baseSaleAttrId, saleAttrName] = this.attrIdAndAttrName.split(":");
      let newSaleAttr = {
        baseSaleAttrId,
        saleAttrName,
        spuSaleAttrValueList: [],
      };
      this.spu.spuSaleAttrList.push(newSaleAttr);
      this.attrIdAndAttrName = "";
    },
    //添加属性值操作
    addSaleAttrValue(row) {
      this.$set(row, "inputVisible", true);
      this.$set(row, "inputValue", "");
    },
    //新增属性值ipunt失去焦点事件
    handleInputConfirm(row) {
      const { baseSaleAttrId, inputValue } = row;
      if (inputValue.trim() == "") {
        this.$message("属性值不能为空");
        return;
      }
      let result = row.spuSaleAttrValueList.some(
        (v) => v.saleAttrValueName == inputValue
      );
      if (result) {
        this.$message("属性值重复！");
        return;
      }
      let newSaleAttrValue = { baseSaleAttrId, saleAttrValueName: inputValue };
      row.spuSaleAttrValueList.push(newSaleAttrValue);
      row.inputVisible = false;
    },
    //保存回调
    async addOruodateSpu() {
      //整理参数
      console.log(this.spuImageList);
      this.spu.supImgeList = this.spuImageList.map((item) => {
        return {
          imgName: item.name,
          imgUrl: item.url || (item.response && item.response.data),
        };
      });
      console.log(this.spu);
      let result = await this.$API.spu.reqAddOrUpdateSpu(this.spu);
      if (result.code == 200) {
        this.$message({ type: "success", message: "保存成功" });
        this.$emit("changeScene", {scene:0,flag:this.spu.id?"修改":"添加"});
        Object.assign(this._data,this.$options.data())
        
      }
    },
    //取消按钮回调
    cancel(){
      this.$emit('changeScene', {scene:0,flag:""});
      //清理数据 避免数据回显
      //0bject.assign  es6中新增的方法可以合并对象
      //组件实例this._data, 可以操作data当中响应式数据
      //this.$options可以获取配置对象，配置对象的data函数执行，返回的响应式数据为空的
      Object.assign(this._data,this.$options.data())
    }
  },
  computed: {
    unSelectSaleAttr() {
      return (this.saleAttrList || []).filter((item) => {
        return (this.spu.spuSaleAttrList || []).every(
          (v) => item.id != v.baseSaleAttrId
        );
      });
    },
    //  return this.spu.spuSaleAttrList.filter(item=>{
    //     return this.saleAttrList.every(v=>item.baseSaleAttrId!=v.id)
    //   })
  },
};
</script>

<style>
</style>